package com.qidian.mespro.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qidian.mespro.mapper.MaterialMapper;
import com.qidian.mespro.mapper.UnitMapper;
import com.qidian.mespro.mapper.WorkflowProductMapper;
import com.qidian.mespro.service.WorkflowProductService;
import com.qidianit.mes.pojo.Material;
import com.qidianit.mes.pojo.Result;
import com.qidianit.mes.pojo.pro.WorkflowProduct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @ Description:
 * @ Author: DuYaTao
 * @ Date: 2025/9/23 - 10:29
 */
@Service
public class WorkflowProductServiceImpl implements WorkflowProductService {

    @Autowired
    private WorkflowProductMapper workflowProductMapper;

    @Autowired
    private MaterialMapper materialMapper;

    @Autowired
    private UnitMapper unitMapper;

    @Override
    public Result<PageInfo<WorkflowProduct>> selectWorkflowProductList(WorkflowProduct workflowProduct, Integer page, Integer size) {
        //开始分页
        PageHelper.startPage(page, size);
        List<WorkflowProduct> workflowProducts = workflowProductMapper.selectWorkflowProductList(workflowProduct);
        for(WorkflowProduct wp:workflowProducts){
            //设置关联的商品
            wp.setMaterial(materialMapper.selectByCode(wp.getProductCode()));
            //取出商品
            Material product = wp.getMaterial();
            if(product!=null){
                //设置关联商品的单位
                wp.getMaterial().setUnit(unitMapper.selectById(product.getUnitId()));
            }

        }
        return Result.success(new PageInfo<>(workflowProducts));
    }

    /**
     * 新增工艺流程关联产品接口
     * @param workflowProduct
     * @return
     */
    @Override
    public Result<WorkflowProduct> addWorkflowProduct(WorkflowProduct workflowProduct) {
        return workflowProductMapper.insertWorkflowProduct(workflowProduct) == 1 ? Result.success() : Result.error("添加失败");
    }

    @Override
    public Result<WorkflowProduct> selectWorkflowProductById(Integer id) {
        return Result.success(workflowProductMapper.selectWorkflowProductById(id));
    }
}
